<template>
  <!-- 最外层的容器 -->
  <view class="my-settle-container">
    <!-- 全选区域 -->
    <label class="radio" @click="changeAllState">
      <radio color="#C00000" :checked="isFullCheck" />
      <text>全选</text>
    </label>
    <!-- 合计区域 -->
    <view class="amount-box">
      合计:
      <text class="amount">￥{{computeAllGoodsPrice}}</text>
    </view>
    <!-- 结算按钮 -->
    <view class="btn-settle" @click="settlement">结算({{checkedCount}})</view>
  </view>
</template>
<script>
import {mapGetters,mapMutations,mapState} from 'vuex'
export default {
  name: 'my-settle',
  computed:{
    ...mapState('m_user',['token']),
    ...mapState('m_cart',['cart']),
    ...mapGetters('m_cart',['checkedCount','total','computeAllGoodsPrice']),
    ...mapGetters('m_user',['addstr']),
    isFullCheck(){
      return this.checkedCount===this.total
    }
  },
  data() {
    return {
      seconds:3,
      timer:null
    };
  },
  methods:{
    ...mapMutations('m_cart',['updateAllState']),
    ...mapMutations('m_user',['updateJumpInfo']),
    changeAllState(){
      // 调用store里面的函数修改所有商品的状态
      this.updateAllState(!this.isFullCheck)
    },
    settlement(){ // 点击结算
      if(!this.checkedCount) return uni.$showMsg('请选择要结算的商品')
      if(!this.addstr) return uni.$showMsg('请选择收货地址')
      if(!this.token) return this.delayJump()
      // 支付功能的实现
      this.payOrder()
    },
     async payOrder(){
      // 1:创建订单
      const orderInfo={
        order_price:0.01,
        consignee_addr:this.addstr,
        goods:this.cart.filter(item=>item.goods_state).map(x=>({
          goods_id:x.goods_id,
          goods_number:x.goods_count,
          goods_price:x.goods_price
        }))
      }
      const {data}=await uni.$http.post('/api/public/v1/my/orders/create',orderInfo)
      // console.log(data);
      if(data.meta.status!==200){
        return uni.$showMsg('创建订单失败！')
      }
      // 把订单编号存起来
      const orderNumber=data.message.order_number
      // 2:订单预支付
      const {data:res}=await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder',{order_number:orderNumber})
      // console.log(res);
      if(res.meta.status!==200){
        return uni.$showMsg('预付订单创建失败！')
      }
      //把订单支付必要的参数存起来：
      const payInfo=res.message.pay
      // 3:发起微信支付
      const [err,succ]=await uni.requestPayment(payInfo)
      if(err) return uni.$showMsg('支付失败')
      // 4：向后端发起一个请求，检查订单状态，是否支付成功
      const {data:res1}=await uni.$http.post('/api/public/v1/my/orders/chkOrder',{order_number:orderNumber})
      console.log(res1);
      if(res1.meta.status!==200){
        return uni.$showMsg('订单支付失败！')
      }
      uni.showToast({
        title:res1.message,
        icon:'none'
      })
    },
    // 倒计时三秒后自动跳转到登录页面
    delayJump(){
      // 3:每一次点击结算按钮,都把data中的秒数重置为3
      this.seconds=3
      // 1：设置定时器，每隔一秒钟给用户一个提示（this.seconds--）
      this.timer=setInterval(()=>{
        // 2:当秒数this.seconds<=0的时候,终止这个定时器,不要再倒计时了,
        //同时还要执行一个跳转，跳到登录页面
        if(this.seconds<=0){
          clearInterval(this.timer)// 清空定时器
          uni.switchTab({ // 跳转
            url:'/pages/my/my',
            success:()=>{
              // 调用修改跳回页面信息的函数
              this.updateJumpInfo({
                opentype:'switchTab',
                from:'/pages/cart/cart'
              })
            }
          })
          return 
        }
        uni.showToast({
          icon:'none',
          title:'请登录后再结算！'+ this.seconds-- +'秒后自动跳转到登录页'
        })
      },1000)
    }
  }
};
</script>

<style lang="scss">
.my-settle-container {
  /* 底部固定定位 */
  position: fixed;
  bottom: 0;
  left: 0;
  /* 设置宽高和背景色 */
  width: 100%;
  height: 50px;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 5px;
  font-size: 14px;

  .radio {
    display: flex;
    align-items: center;
  }

  .amount {
    color: #c00000;
  }

  .btn-settle {
    height: 50px;
    min-width: 100px;
    background-color: #c00000;
    color: white;
    line-height: 50px;
    text-align: center;
    padding: 0 10px;
  }
}
</style>
